package com.guodi.map.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.secure.LoginUser;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapBookMark;
import com.guodi.map.entity.MapRoam;
import com.guodi.map.service.IMapRoamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @描述:  路线记录前端控制器
* @作者: 陈宏成
* @日期: 2021-04-16
*/
@RestController
@RequestMapping("/MapRoam")
@Api(value = "API - MapRoamController", tags = "路线记录表")
public class MapRoamController extends BaseController {

    @Resource
    private IMapRoamService iMapRoamService;

    /**
     * @描述：新增路线记录
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增路线记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "路线名称", required = true, dataType = "string", paramType = "query",example = "长江大道"),
            @ApiImplicitParam(name = "flightPath", value = "路线坐标点集合json", required = true, dataType = "string", paramType = "query",example = "{\"position\":[{\"pointName\":\"点1\",\"fov\":55,\"heading\":11.7277,\"position\":{\"longitude\":4247.3333,\"latitude\":238.666,\"z\":36.3333},\"tilt\":86.92222},{\"pointName\":\"点2\",\"fov\":55,\"heading\":11.7277,\"position\":{\"longitude\":4247.3333,\"latitude\":238.666,\"z\":36.3333},\"tilt\":86.92222}]}"),
            @ApiImplicitParam(name = "remark", value = "备注",  dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<MapRoam> save(@ApiIgnore MapRoam mapRoam){
        // 新增前的验证数据，填充数据
        R prepareBeforeSaveResult = this.prepareBeforeSave(mapRoam);
        if (prepareBeforeSaveResult != null){
            return prepareBeforeSaveResult;
        }
        boolean save = this.iMapRoamService.save(mapRoam);
        if (save){
            return R.data(mapRoam);
        }else{
            return R.fail(StatusCode.ERROR_CODE_40005,"新增失败");
        }
    }

    /**
     * @描述：修改路线记录
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改路线记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "路线id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "路线名", required = true, dataType = "string", paramType = "query",example = "长江大道"),
            @ApiImplicitParam(name = "flightPath", value = "路线坐标点集合json", required = true, dataType = "string", paramType = "query",example = "{\"position\":[{\"pointName\":\"点1\",\"fov\":55,\"heading\":11.7277,\"position\":{\"longitude\":4247.3333,\"latitude\":238.666,\"z\":36.3333},\"tilt\":86.92222},{\"pointName\":\"点2\",\"fov\":55,\"heading\":11.7277,\"position\":{\"longitude\":4247.3333,\"latitude\":238.666,\"z\":36.3333},\"tilt\":86.92222}]}"),
            @ApiImplicitParam(name = "remark", value = "备注",  dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<MapRoam> update(@ApiIgnore MapRoam mapRoam){
        // 新增前的验证数据，填充数据
        R prepareBeforeUpdateResult = this.prepareBeforeUpdate(mapRoam);
        if (prepareBeforeUpdateResult != null){
            return prepareBeforeUpdateResult;
        }
        boolean save = this.iMapRoamService.updateById(mapRoam);
        if (save){
            return R.data(mapRoam);
        }else{
            return R.fail(StatusCode.ERROR_CODE_40005,"修改失败");
        }
    }

    /**
     * @描述：删除路线记录
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除路线记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "主键id，如果多个，英文逗号隔开", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R delete(String ids){
        LoginUser user = getUser();
        if (!StringUtils.hasText(ids)){
            return R.fail("");
        }
        List<String> idList = Arrays.asList(ids.trim().split(","));
        // 查询
        LambdaQueryWrapper<MapRoam> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.in(MapRoam::getId,idList);
        lambdaQueryWrapper.eq(MapRoam::getCreator,user.getUserId().toString());
        List<MapRoam> list = this.iMapRoamService.list(lambdaQueryWrapper);
        // 删除
        List<String> deleteIds = list.stream().map(MapRoam::getId).collect(Collectors.toList());
        this.iMapRoamService.removeByIds(deleteIds);
        return R.data(list);
    }

    /**
     * @描述：获取路线记录详情
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    @PostMapping("/detail")
    @ApiOperation(value = "获取路线记录详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R<MapRoam> detail(String id){
        if (!StringUtils.hasText(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"主键id不能为空");
        }
        LoginUser user = getUser();
        LambdaQueryWrapper<MapRoam> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(MapRoam::getCreator,user.getUserId().toString());
        lambdaQueryWrapper.eq(MapRoam::getId,id);
        MapRoam roam = this.iMapRoamService.getOne(lambdaQueryWrapper, false);
        if (roam == null){
            return R.fail(StatusCode.ERROR_CODE_40005,"记录不存在");
        }
        return R.data(roam);
    }

    /**
     * @描述：获取路线记录列表
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    @PostMapping("/list")
    @ApiOperation(value = "获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码",  dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "书签名称",  dataType = "string", paramType = "query"),
    })
    public R list(@ApiIgnore Page page, String name){
        LoginUser user = getUser();
        LambdaQueryWrapper<MapRoam> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(StringUtils.hasText(name), MapRoam::getName, StringUtils.hasText(name)?name.trim():name);
        lambdaQueryWrapper.eq(MapRoam::getCreator,user.getUserId().toString());
        lambdaQueryWrapper.orderByDesc(MapRoam::getCreateTime);
        lambdaQueryWrapper.orderByDesc(MapRoam::getId);
        Page page1 = this.iMapRoamService.page(page, lambdaQueryWrapper);

        return R.data(page1);
    }

    /**
     * @描述：修改前的准备，包括验证数据和填充数据
     * @入参：mapRoam
     * @出参：如果返回null，则表示无任何问题，如果有返回，则说明有问题需要返回给前端
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    private R<MapBookMark> prepareBeforeUpdate(MapRoam mapRoam){
        LoginUser user = getUser();
        // 验证非空数据项
        if (!StringUtils.hasText(mapRoam.getId())){
            return R.fail(StatusCode.ERROR_CODE_40005,"主键id不能为空");
        }
        if (!StringUtils.hasText(mapRoam.getName())){
            return R.fail(StatusCode.ERROR_CODE_40005,"书签名不能为空");
        }
        if (!StringUtils.hasText(mapRoam.getFlightPath())){
            return R.fail(StatusCode.ERROR_CODE_40005,"范围不能为空");
        }
        // 验证重名数据项，如果存在同名，还不是自己，就报错
        LambdaQueryWrapper<MapRoam> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(MapRoam::getName,mapRoam.getName());
        lambdaQueryWrapper.eq(MapRoam::getCreator,user.getUserId().toString());
        List<MapRoam> list = this.iMapRoamService.list(lambdaQueryWrapper);
        if (list != null && !list.isEmpty() && !list.get(0).getId().equals(mapRoam.getId())){
            return R.fail(StatusCode.ERROR_CODE_40005,"该路线名已存在");
        }
        // 判断是否是自己的记录
        MapRoam roam = this.iMapRoamService.getById(mapRoam.getId());
        if (roam == null){
            return R.fail(StatusCode.ERROR_CODE_40005,"记录不存在");
        }
        if (!user.getUserId().toString().equals(roam.getCreator())){
            return R.fail(StatusCode.ERROR_CODE_40005,"不能修改他人记录");
        }
        // 去除首尾空格
        mapRoam.setName(mapRoam.getName().trim());
        mapRoam.setFlightPath(mapRoam.getFlightPath().trim());
        // 填充创建人和创建时间
        mapRoam.setCreator(roam.getCreator());
        mapRoam.setCreateTime(roam.getCreateTime());
        mapRoam.setModifier(user.getUserId().toString());
        mapRoam.setModifyTime(new Date());
        return null;
    }

    /**
     * @描述：新增前的准备，包括验证数据和填充数据
     * @入参：mapRoam
     * @出参：如果返回null，则表示无任何问题，如果有返回，则说明有问题需要返回给前端
     * @作者: 陈宏成
     * @日期: 2021-04-16
     */
    private R prepareBeforeSave(MapRoam mapRoam){
        LoginUser user = getUser();
        // 验证非空数据项
        if (!StringUtils.hasText(mapRoam.getName())){
            return R.fail(StatusCode.ERROR_CODE_40005,"路线名不能为空");
        }
        if (!StringUtils.hasText(mapRoam.getFlightPath())){
            return R.fail(StatusCode.ERROR_CODE_40005,"路线范围不能为空");
        }
        // 验证重名数据项
        LambdaQueryWrapper<MapRoam> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(MapRoam::getName,mapRoam.getName());
        lambdaQueryWrapper.eq(MapRoam::getCreator,user.getUserId().toString());
        List<MapRoam> list = this.iMapRoamService.list(lambdaQueryWrapper);
        if (list != null && !list.isEmpty()){
            return R.fail(StatusCode.ERROR_CODE_40005,"该路线名已存在");
        }
        // 如果没有id，默认给一个
        if (!StringUtils.hasText(mapRoam.getId())){
            mapRoam.setId(UuidUtil.get32UUID());
        }
        // 去除首尾空格
        mapRoam.setName(mapRoam.getName().trim());
        mapRoam.setFlightPath(mapRoam.getFlightPath().trim());
        // 填充创建人和创建时间
        mapRoam.setCreator(user.getUserId().toString());
        mapRoam.setCreateTime(new Date());
        mapRoam.setModifier(null);
        mapRoam.setModifyTime(null);
        return null;
    }

}
